package com.tlgen.zero.config;

import com.alibaba.fastjson.JSONObject;
import com.tlgen.zero.model.DataResult;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

import static com.tlgen.zero.utils.ZeroUtils.startZero;

public class ZeroInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return !toResult(response, startZero(request));
    }

    private static boolean toResult(HttpServletResponse response, DataResult dataResult) {
        if (Objects.nonNull(dataResult) && Objects.equals(1, dataResult.getFlag())) { // 是否是可寻接口 0.否 1 .是
            try {
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONObject.toJSONString(dataResult.getData()));
                writer.flush();
                writer.close();
                return true; // 返回 true 表示继续执行 controller 方法，返回 false 表示中断
            } catch (IOException ignored) {
            }
        }
        return false; // 直接返回了, 不走后边的 controller
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在 Controller 方法调用后、视图渲染前执行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在视图渲染完成后执行，通常用于资源清理等操作
    }
}
